package com.huang.day7;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author HuangShen
 * @Description
 * @create 2021-04-06 12:12
 */
public class ReentrantLockTest {

    public static void main(String[] args) {


        ChopstickReen chopstick1 = new ChopstickReen("1");
        ChopstickReen chopstick2 = new ChopstickReen("2");
        ChopstickReen chopstick3 = new ChopstickReen("3");
        ChopstickReen chopstick4 = new ChopstickReen("4");
        ChopstickReen chopstick5 = new ChopstickReen("5");


        new PhilosopherReet("员工1",chopstick1,chopstick2).start();
        new PhilosopherReet("员工2",chopstick2,chopstick3).start();
        new PhilosopherReet("员工3",chopstick3,chopstick4).start();
        new PhilosopherReet("员工4",chopstick3,chopstick4).start();
        new PhilosopherReet("员工5",chopstick4,chopstick5).start();


    }



}
class PhilosopherReet extends  Thread{

    ChopstickReen left;
    ChopstickReen right;

    public PhilosopherReet(String name, ChopstickReen left, ChopstickReen right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true){
           if (left.tryLock()){
               try {
                   if (right.tryLock()) {

                       try {
                           eat();
                       }finally {
                           right.unlock();
                       }
                   }
               }finally {
                   left.unlock();
               }

           }
        }
    }


    private  void  eat(){
        try {
            System.out.println(Thread.currentThread().getName()+"--eating.......");
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class  ChopstickReen extends ReentrantLock {
    String name;
    public ChopstickReen(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "筷子{"+name+"}";
    }
}